package com.mapforge.gui;

import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JSlider;

/**
 * The {@link ClickableSlider} is a {@link JSlider} which allows a user to click
 * on the slider to move its slide.
 * 
 * @author Will Morrison
 */
public class ClickableSlider extends JSlider {

	/**
	 * Default serial version ID, here to remove warnings.
	 */
	private static final long serialVersionUID = 1L;

	public ClickableSlider(int orientation, int min, int max, int value) {
		super(orientation, min, max, value);
		SliderMouseListener listener = new SliderMouseListener();
		addMouseListener(listener);
		addMouseMotionListener(listener);
	}

	private class SliderMouseListener extends MouseAdapter {
		private boolean dragged;

		public SliderMouseListener() {
			dragged = false;
		}

		public void mouseDragged(MouseEvent e) {
			dragged = true;
		}

		public void mouseReleased(MouseEvent e) {
			if (!dragged) {
				setClickableSlider(e);
			}
			dragged = false;
		}

		private void setClickableSlider(MouseEvent e) {
			Rectangle rect = getBounds();
			double length = rect.getWidth();
			int mouseX = e.getX();
			int max = getMaximum();
			double ratio = mouseX / length;
			double value = max * ratio;
			setValue((int) value);
		}
	}
}